/*
 *  Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 *  This file is part of e3utils.
 *
 *  e3utils is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  e3utils is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with e3utils. If not, see <https://www.gnu.org/licenses/>.
 */

package errors

import (
	"errors"
	"fmt"
	"runtime"
)

type stackError struct {
	msg   string
	stack string
}

func (e *stackError) Error() string {
	return e.msg + "\n" + e.stack
}

func NewOrWrapWithStack(err error, msg string) error {
	if err == nil {
		return newWithStack(msg, 2)
	} else {
		return wrapWithStack(err, msg, 2)
	}
}

func NewWithStack(msg string) error {
	return newWithStack(msg, 2)
}

func NewWithStackPrintf(format string, a ...any) error {
	msg := fmt.Sprintf(format, a...)
	return newWithStack(msg, 2)
}

func WrapWithStack(err error, msg string) error {
	return wrapWithStack(err, msg, 2)
}

func newWithStack(msg string, skip int) error {
	funcName, file, line, _ := runtime.Caller(skip)
	format := "func: %s\t%s:%d"
	stack := fmt.Sprintf(format, runtime.FuncForPC(funcName).Name(), file, line)
	return &stackError{msg: msg, stack: stack}
}

func wrapWithStack(err error, msg string, skip int) error {
	if err == nil {
		return nil
	}
	funcName, file, line, _ := runtime.Caller(skip)
	format := "func: %s\t%s:%d"
	stack := fmt.Sprintf(format, runtime.FuncForPC(funcName).Name(), file, line)
	var e *stackError
	switch {
	case errors.As(err, &e):
		return &stackError{
			msg:   msg + " -> " + e.msg,
			stack: stack + "\n" + e.stack,
		}
	default:
		return &stackError{
			msg:   msg + " -> " + err.Error(),
			stack: stack,
		}
	}
}
